package com.leetcode.search.backtracking;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;

/**
 * @author Dennis Li
 * @date 2020/7/27 19:20
 */
public class PalindromePartitioning_131 {

    private final List<List<String>> res = new ArrayList<>();

    public List<List<String>> partition(String s) {
        if (s.equals("")) return res;
        backtrack(s, new LinkedList<>());
        return res;
    }

    private void backtrack(String str, LinkedList<String> list) {
        if (str.length() == 0) {
            res.add(new ArrayList<>(list));
            return;
        }
        for (int i = 0; i < str.length(); i++) {
            String temp = str.substring(0, i + 1);
            if (isPalindrome(temp)) {
                list.add(temp);
                backtrack(str.substring(i + 1), list);
                list.removeLast();
            }
        }
    }

    private boolean isPalindrome(String str) {
        if (str.equals("")) return false;
        int i = 0, j = str.length() - 1;
        while (i < j) {
            if (str.charAt(i++) != str.charAt(j--)) return false;
        }
        return true;
    }

}
